# import os
import shutil
import json
from PydubCore import PydubCore
from flask import *
from flask_cors import *
from werkzeug.utils import *
import traceback

app = Flask(__name__, static_folder='uploads')
CORS(app, supports_credentials=True)

UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['wav', 'mp3'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

is_dev = False

check_songs = False
# paragraph_filename = {'1-01': 'x.wav', '1-02': '0.2 虫.wav', '2-03': '5.2 火焰山.wav', '2-04': '豆豆音1.wav',
#                       '2-05': '5.1 冷风吹.wav', '2-06': '3.2 人声_前方有火焰山.wav', '2-07': '敲锅1.wav',
#                       '3-01': '1. 人声_小朋友们探险开始了+哇.wav', '5-08': '3.2 人声_前方有火焰山.wav', '5-09': '3.1 人声_冷风来了.wav',
#                       '5-10': '5.1 熊2.wav', '5-11': '3.2 人声_蜜蜂来了.wav', '5-12': '3.1 人声_熊来了.wav', '7-13': '5.1 冷风吹.wav',
#                       '7-14': '3.2 人声_前方有火焰山.wav', '7-15': '敲锅1.wav', '7-16': '3.1 人声_冷风来了.wav',
#                       '7-17': '9. 人声_探险成功+鼓掌声.wav', '8-01': '6. 人声_虚惊一场.wav', '10-01': '敲锅1.wav',
#                       '11-18': '8.2 人声_天亮了.wav', '11-19': '8.1 人声_天黑了.wav', '9-01': '9. 人声_探险成功+鼓掌声.wav'}
# paragraph_condition = {'11': True, '4': ['2', '3'], '5': '3', '6': ['3'], '7': '300', '72': '3', '51': '2',
#                        '52': '1 3 2 4 5'}
paragraph_filename = {}
paragraph_condition = {'11': False, '4': ['1', '1'], '5': '2', '6': ['2'], '7': 'differ'}

execer = PydubCore(paragraph_filename, paragraph_condition)


@app.route('/')
def hello_world():
    global execer
    print(execer.paragraph_filename)
    print(execer.paragraph_condition)
    return 'Hello World!'


@app.route('/get-one', methods=['POST'])
def get_one():
    global execer
    p = request.json['p']
    p = p + '-'
    res_new_list = {}
    for k in execer.paragraph_filename:
        if k.find(p) != -1 and k.startswith(p):
            res_new_list[k] = execer.paragraph_filename[k]
    return json.dumps(res_new_list)


@app.route('/get-all', methods=['GET'])
def get_all():
    global execer
    return json.dumps(execer.paragraph_filename)


@app.route('/delete', methods=['POST'])
def delete():
    global execer
    try:
        p = request.json['paragraph']
        del execer.paragraph_filename[p]
        os.remove('uploads/' + p)
        res_dict = {'success': True, 'data': ''}
        return json.dumps(res_dict)
    except Exception as e:
        res_dict = {'success': False, 'data': repr(e)}
        return res_dict


@app.route('/refresh-all', methods=['POST'])
def refreshall():
    global execer
    global is_dev
    if not is_dev:
        shutil.rmtree(UPLOAD_FOLDER)
        execer.paragraph_filename.clear()
        execer.paragraph_condition.clear()
        os.mkdir(UPLOAD_FOLDER)
        execer.paragraph_condition = {'11': True, '4': ['1', '1'], '5': '2', '6': ['2'], '7': 'differ'}
        execer.load_prj_s()
    res_dict = {'success': True, 'data': ''}
    return json.dumps(res_dict)


@app.route('/add-condition', methods=['POST'])
def add_condition():
    global execer
    paragraph_strx = request.json['paragraph']
    condition_str = request.json['condition']
    execer.paragraph_condition[paragraph_strx] = condition_str
    res_dict = {'success': True, 'data': ''}
    return json.dumps(res_dict)


@app.route('/upload', methods=['POST'])
def file_upload():
    global execer
    paragraph = request.form['paragraph']
    print('paragraph is : ' + paragraph)
    file = request.files['file']
    if file:
        filename = file.filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], paragraph))
        execer.paragraph_filename[paragraph] = filename
        res_dict = {'success': True, 'url': 'uploads/' + paragraph, 'filename': filename}
        return json.dumps(res_dict)
    return 'Error'


@app.route('/execution', methods=['POST'])
def execution():
    try:
        global execer
        return execer.do_exec()
    except Exception as e:
        res_dict = {'success': False, 'data': traceback.format_exc()}
        return json.dumps(res_dict)


@app.route('/modify-tags', methods=['PUT'])
def modify_check_Tag():
    global check_songs
    global is_dev
    is_dev = not is_dev
    check_songs = not check_songs
    res_dict = {'success': True}
    return json.dumps(res_dict)


@app.route('/save-prj', methods=['POST'])
def save_prj():
    global execer
    try:
        prj_name = request.json['prjname']
        execer.save_prj(prj_name)
        res_dict = {'success': True}
        return json.dumps(res_dict)
    except Exception as e:
        res_dict = {'success': False, 'data': repr(e) + '\n保存失败'}
        return res_dict


@app.route('/load-prj', methods=['POST'])
def load_prj():
    global execer
    try:
        prj_name = request.json['prjname']
        execer.load_prj(prj_name)
        res_dict = {'success': True, 'data': execer.paragraph_condition}
        return json.dumps(res_dict)
    except Exception as e:
        res_dict = {'success': False, 'data': repr(e) + '\n载入失败'}
        return res_dict


@app.route('/recent-prj', methods=['GET'])
def recent_prj():
    global execer
    res_dict = {'success': True, 'data': execer.loadable_list}
    return json.dumps(res_dict)


@app.route('/delete-prj', methods=['POST'])
def delete_prj():
    global execer
    try:
        prj_name = request.json['prjname']
        execer.delete_prj(prj_name)
        res_dict = {'success': True, 'data': '删除成功'}
        return json.dumps(res_dict)
    except Exception as e:
        res_dict = {'success': False, 'data': repr(e) + '\n删除失败'}
        return res_dict


@app.route('/check-prj', methods=['POST'])
def is_prj_ok():
    global execer
    try:
        #重新刷新全部有效音频
        execer.set_all_songs()
        # 检查背景音1至少有一个
        res1, _ = execer.find_songs_by_p(1)
        if len(res1) <= 0:
            res_dict = {'success': False, 'data': '项目校验失败：背景音一至少有一个'}
            return json.dumps(res_dict)
        # 检查背景音2至少有一个
        res2, _ = execer.find_songs_by_p(2)
        if len(res2) <= 0:
            res_dict = {'success': False, 'data': '项目校验失败：背景音二至少有一个'}
            return json.dumps(res_dict)
        # 检查3和6项音频数量相等
        res5, _ = execer.find_songs_by_p(5)
        res7, _ = execer.find_songs_by_p(7)
        if len(res5) != len(res7):
            res_dict = {'success': False, 'data': '项目校验失败：动作指示信号与持续做动作音中的音频数量不等'}
            return json.dumps(res_dict)

        # #查重
        # tmp = []
        # for key in execer.paragraph_filename:
        #     if tmp.__contains__(execer.paragraph_filename[key]):
        #         res_dict = {'success': False, 'data': '项目校验失败：有重名的文件存在： '+execer.paragraph_filename[key]}
        #         return json.dumps(res_dict)
        #     else:
        #         tmp.append(execer.paragraph_filename[key])

        #正确！
        res_dict = {'success': True, 'data': '项目校验成功'}
        return json.dumps(res_dict)
    except Exception as e:
        res_dict = {'success': False, 'data': repr(e) + '\n校验项目失败'}
        return res_dict


if __name__ == '__main__':
    from werkzeug.contrib.fixers import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.run(host='0.0.0.0')

